package tn.orange.canreminder;

import java.io.IOException;
import java.util.Collections;
import java.util.List;

import tn.orange.canreminder.adapter.PlaceFavoriteAdapter;
import tn.orange.canreminder.location.MyLocation;
import tn.orange.canreminder.location.MyLocation.LocationResult;
import tn.orange.canreminder.sqlite.Place;
import tn.orange.canreminder.sqlite.PlaceDBDistanceComparator;
import tn.orange.canreminder.sqlite.PlaceDao;
import tn.orange.canreminder.sqlite.PlaceDaoImp;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.TextView;

public class ListFavoritePlaceActivity extends Activity {

	private ListView listView;
	private Location location;
	private List<Place> places;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.places_favorite);

		listView = (ListView) findViewById(R.id.list_places);
		LocationResult locationResult = new LocationResult() {

			@Override
			public void gotLocation(Location location1) {
				// TODO Auto-generated method stub
				location = location1;
			}
		};

		MyLocation myLocation = new MyLocation();

		myLocation.getLocation(ListFavoritePlaceActivity.this, locationResult);

		PlaceAsyncTask asyncTask = new PlaceAsyncTask();
		asyncTask.execute();

	}

	public void onDelClick(View v) {
		// TODO Auto-generated method stub
		PlaceDao placeDao = new PlaceDaoImp(getApplicationContext());
		placeDao.deletePlace((Long) v.getTag());
		PlaceAsyncTask asyncTask = new PlaceAsyncTask();
		asyncTask.execute();
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();

	}

	private class PlaceAsyncTask extends AsyncTask<Location, Void, List<Place>> {
		private final ProgressDialog dialog = new ProgressDialog(
				ListFavoritePlaceActivity.this);

		// can use UI thread here
		protected void onPreExecute() {
			this.dialog.setMessage("Veuillez patienter...");
			this.dialog.setCancelable(false);
			this.dialog.show();
		}

		// automatically done on worker thread (separate from UI thread)
		protected List<Place> doInBackground(final Location... args) {

			List<Place> places = null;

			try {
				Thread.sleep(10000);
			} catch (InterruptedException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			PlaceDao placeDao = new PlaceDaoImp(ListFavoritePlaceActivity.this);
			try {
				places = placeDao.getAllPlace();

			} catch (Exception e) {
				// TODO Auto-generated catch block
				cancel(false);
			}
			return places;
		}

		@Override
		protected void onCancelled() {
			// TODO Auto-generated method stub
			super.onCancelled();
			if (this.dialog.isShowing()) {
				this.dialog.dismiss();
			}
			showErrorDialog("Problème de connexion ");

		}

		// can use UI thread here
		protected void onPostExecute(final List<Place> places1) {
			if (this.dialog.isShowing()) {
				this.dialog.dismiss();

			}
			places = places1;

			for (Place place : places) {
				Location placeLocation = new Location("gps");
				float longitude = Float.parseFloat(place.getLongitude());
				float latitude = Float.parseFloat(place.getLatitude());
				placeLocation.setLatitude(longitude);
				placeLocation.setLongitude(latitude);
				String distance = "" + location.distanceTo(placeLocation);
				int pos = distance.indexOf(".");
				distance = distance.substring(0, pos + 2);
				place.setDistance(Double.parseDouble(distance));
			}

			PlaceDBDistanceComparator comparator = new PlaceDBDistanceComparator();
			Collections.sort(places, comparator);

			listView.setAdapter(new PlaceFavoriteAdapter(
					ListFavoritePlaceActivity.this, places, location));

		}

		private void showErrorDialog(String message) {
			AlertDialog alertDialog = new AlertDialog.Builder(
					ListFavoritePlaceActivity.this).create();
			alertDialog.setTitle("Erreur");
			alertDialog.setMessage(message);
			alertDialog.setButton("Ok", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {

				}
			});

			alertDialog.show();
		}
	}

	public void OnHomeClick(View v) {
		Intent intent = new Intent(getApplicationContext(),
				DashboardActivity.class);
		startActivity(intent);
	}

	public void OnClickMap(View v) throws IOException {

		int position = (Integer) v.getTag();
		Place place = places.get(position);

		Intent intent1 = new Intent(android.content.Intent.ACTION_VIEW,
				Uri.parse("http://maps.google.com/?saddr="
						+ location.getLatitude() + ","
						+ location.getLongitude() + "&daddr="
						+ place.getLongitude() + "," + place.getLatitude()));
		startActivity(intent1);

	}

	public void OnFavClick(View v) {
		CheckBox box = (CheckBox) v;
		if (box.isChecked()) {
			PlaceDao placeDao = new PlaceDaoImp(ListFavoritePlaceActivity.this);
			Place place = places.get((Integer) v.getTag());

			tn.orange.canreminder.sqlite.Place placedb = new tn.orange.canreminder.sqlite.Place();

			placedb.setAdresse(place.getAdresse());
			placedb.setCategory(" ");
			placedb.setImage("image");
			placedb.setLatitude("" + place.getLatitude());
			placedb.setLongitude("" + place.getLongitude());
			placedb.setNom(place.getNom());
			placedb.setTelephone(place.getTelephone());

			placeDao.insertPlace(placedb);
			box.setChecked(true);
		} else {
			PlaceDao placeDao = new PlaceDaoImp(getApplicationContext());
			int pos = (Integer) v.getTag();
			placeDao.deletePlace((places.get(pos).getNom()));
			box.setChecked(false);

		}

		PlaceAsyncTask asyncTask = new PlaceAsyncTask();
		asyncTask.execute();
	}
}
